/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package org.exmaple.bean;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 手动配置JdbcTemplate, 自动spring会自己注入
 */
@Configuration
public class DataSourceConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceConfig.class);
    @Value("spring.datasource.driver-class-name")
    private String driver;
    @Value("spring.datasource.url")
    private String url;

    @Autowired
    private Environment env;

    @Bean(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(driver);
        hikariConfig.setJdbcUrl(url);
        String username = env.getProperty("spring.datasource.username", "sa");
        hikariConfig.setUsername(username);
        String password = env.getProperty("spring.datasource.password", "");
        hikariConfig.setPassword(password);
        LOGGER.info(String.format("build connectorPool for at %s use %s", url, driver));
        HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);

        return new JdbcTemplate(hikariDataSource);
    }
}
